/**
 * 区域相关API
 * 对应后端RegionRouter.js中的路由
 */
import api, { extractData } from './axios';

/**
 * 区域接口定义
 */
export interface Region {
  id?: string;                // 前端使用的ID
  _id?: string;               // MongoDB的文档ID
  title: string;              // 区域标题，必填
  value: string;              // 区域值，必填且唯一
  description?: string;       // 区域描述，可选
  departmentType?: string;    // 部门类型，枚举值
  seqId?: number;             // 序列ID，唯一
}

/**
 * 获取所有区域列表
 * 对应后端GET /adminapi/regions路由
 */
export const getRegions = async () => {
  try {
    const response = await api.get('/regions');
    return extractData(response);
  } catch (error) {
    console.error('获取区域列表失败:', error);
    // 修改为返回空数组而不是抛出错误
    return [];
  }
};

/**
 * 获取单个区域详情
 * 对应后端GET /adminapi/regions/:id路由
 */
export const getRegion = async (id: string | number) => {
  try {
    const response = await api.get(`/regions/${id}`);
    return extractData(response);
  } catch (error) {
    console.error(`获取区域详情失败，id=${id}:`, error);
    throw error;
  }
};

/**
 * 获取用户可访问的区域列表
 * 对应后端GET /adminapi/regions/accessible路由
 */
export const getUserAccessibleRegions = async () => {
  try {
    const timeStamp = new Date().getTime(); // 添加时间戳防止缓存
    const response = await api.get(`/regions/accessible?_t=${timeStamp}`);
    return extractData(response);
  } catch (error) {
    console.error('获取用户可访问区域失败:', error);
    // 发生错误时返回空数组
    return [];
  }
};

/**
 * 更新区域
 * 对应后端PUT /adminapi/regions/:id路由
 */
export const updateRegion = async (id: string | number, data: Partial<Region>) => {
  try {
    // 确保data中不包含id和_id字段，避免MongoDB文档ID冲突
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { id: _, _id: __, ...updateData } = data;
    
    const response = await api.put(`/regions/${id}`, updateData);
    return extractData(response);
  } catch (error) {
    console.error(`更新区域失败，id=${id}:`, error);
    throw error;
  }
};

/**
 * 删除区域
 * 对应后端DELETE /adminapi/regions/:id路由
 */
export const deleteRegion = async (id: string | number) => {
  try {
    const response = await api.delete(`/regions/${id}`);
    return response.data;
  } catch (error) {
    console.error(`删除区域失败，id=${id}:`, error);
    throw error;
  }
};

/**
 * 添加区域
 * 对应后端POST /adminapi/regions路由
 */
export const addRegion = async (data: Partial<Region>) => {
  try {
    const response = await api.post('/regions', data);
    return extractData(response);
  } catch (error) {
    console.error('添加区域失败:', error);
    throw error;
  }
};

/**
 * 根据编码获取区域
 * 对应后端GET /adminapi/regions/values/:value路由
 */
export const getRegionByValue = async (value: string) => {
  try {
    const response = await api.get(`/regions/values/${value}`);
    return extractData(response);
  } catch (error) {
    console.error(`根据编码获取区域失败，value=${value}:`, error);
    throw error;
  }
};

// 导出默认对象
export default {
  getRegions,
  getRegion,
  getUserAccessibleRegions,
  updateRegion,
  deleteRegion,
  addRegion,
  getRegionByValue
}; 